#region Using directives
using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using System.IO;
#endregion

namespace SharePointer.FeatureReceivers
{
    class TimerJobSchedulerFeature : SPFeatureReceiver
    {
        const string TimerJobName = "TimerJobScheduler";
        SPSite Site;
        SPWeb RootWeb;

        public override void FeatureInstalled(SPFeatureReceiverProperties properties)
        {
            ;
        }

        public override void FeatureUninstalling(SPFeatureReceiverProperties properties)
        {
            ;
        }

        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            try
            {
                Site = properties.Feature.Parent as SPSite;
                RootWeb = Site.RootWeb;

                DeleteListTemplateIfExist("TimerJobSchedule");

                // Add STP to the List Template Gallery... It will overwrite is the file already exists
                AddListTemplateToGallery(@"C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\FEATURES\TimerJobScheduler\TimerJobSchedule.stp");

                try
                {
                    //Create the List from the List Template
                    if (DoesListExist(RootWeb.Lists))
                    {
                        //Delete The List
                        RootWeb.Lists["TimerJobSchedule"].Delete();
                    }
                   
                    //Create The List
                    Guid TimerJobScheduler = RootWeb.Lists.Add("TimerJobSchedule", "This list contains Timer Job Schedules", GetListTemplate("TimerJobSchedule"));
                    
                }
                catch (Exception ex)
                {
                    // Add Logging here - Log.Write(ex);
                    throw new Exception("The TimerJobSchedule list cannot be created. Delete this list then try again to reactivate this feature.");
                }

                
                // make sure the job isn't already registered
                DeleteJob(properties);

                // install the job
                SharePointer.Utilities.TimerJobScheduler ScheduledTimerJob = new SharePointer.Utilities.TimerJobScheduler(TimerJobName, Site.WebApplication);
                SPMinuteSchedule schedule = new SPMinuteSchedule();
                schedule.BeginSecond = 0;
                schedule.EndSecond = 59;
                schedule.Interval = 2;
                ScheduledTimerJob.Schedule = schedule;
                ScheduledTimerJob.Update();

            }
            catch (Exception ex)
            {
                // Add Logging here - Log.Write(ex);
                throw ex;
            }
            finally
            {
                //Clean up
            }
        }

        private bool DoesListExist(SPListCollection sPListCollection)
        {
            foreach (SPList List in sPListCollection)
            {
                if (List.Title == "TimerJobSchedule")
                {
                    return true;
                }
            }
            return false;
        }

        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            Site = properties.Feature.Parent as SPSite;
            RootWeb = Site.RootWeb;

            //Delete the TimerJobSchedule List
            if (DoesListExist(RootWeb.Lists))
            {
                RootWeb.Lists["TimerJobSchedule"].Delete();
            }

            DeleteListTemplateIfExist("TimerJobSchedule");

            DeleteJob(properties);
        }

        public void DeleteJob(SPFeatureReceiverProperties properties)
        {
            try
            {
                Site = properties.Feature.Parent as SPSite;
                // delete the job
                foreach (SPJobDefinition job in Site.WebApplication.JobDefinitions)
                {
                    if (job.Name == TimerJobName || job.Title == TimerJobName)
                    {
                        try
                        {
                            job.Delete();
                        }
                        catch (Exception ex)
                        {
                            // Add Logging here - Log.Write(ex);
                        }
                    }
                }

                
            }
            catch (Exception ex)
            {
                // Add Logging here - Log.Write(ex);
                throw ex;
            }
            finally
            {
                //Clean up
            }
        }

        private SPListTemplate GetListTemplate(string TemplateName)
        {
            try
            {
                SPListTemplateCollection SiteTemplates = Site.GetCustomListTemplates(RootWeb);
                foreach (SPListTemplate ThisTemplate in SiteTemplates)
                {
                    if (ThisTemplate.Name.ToString() == TemplateName)
                    {
                        return ThisTemplate;
                    }
                }
            }
            catch (Exception ex)
            {
                // Add Logging here - Log.Write(ex);
                throw ex;
            }
            finally
            {
                //RootWeb.Dispose();
            }


            return null;
        }

        private void DeleteListTemplateIfExist(string TemplateName)
        {
            try
            {
                SPListItemCollection SiteTemplates = Site.RootWeb.Lists["List Template Gallery"].Items;
                for(int i = 0; i <= SiteTemplates.Count -1; i++)
                {
                    if (SiteTemplates[i].Title.ToString() == TemplateName)
                    {
                        SiteTemplates[i].Delete();
                    }
                }
            }
            catch (Exception ex)
            {
                // Add Logging here - Log.Write(ex);
                throw ex;
            }
            finally
            {
                //Clean up
            }

        }

        private void AddListTemplateToGallery(string templatePath)
        {

            try
            {
                SPDocumentLibrary TemplatesList = (SPDocumentLibrary)Site.RootWeb.Lists["List Template Gallery"];
                FileInfo TemplateFile = new FileInfo(templatePath);
                byte[] FileContent = System.IO.File.ReadAllBytes(TemplateFile.FullName);
                SPFile NewTemplate = TemplatesList.RootFolder.Files.Add(TemplateFile.Name, FileContent, true);
                NewTemplate.Update();
            }
            catch (Exception ex)
            {
                // Add Logging here - Log.Write(ex);
                throw ex;
            }
        }

    }
}
